package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.BusServiceItem;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.HistoricComment;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBusServiceItemService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BaseException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class CarPackgeAduitServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBusServiceItemService busServiceItemService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private IStatementService serviceItemService;

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }


    @Override
    public TablePageInfo<CarPackageAudit> todoQuery(CarPackageAuditQuery qo) {
        //根据套餐审核的下拉框value找到最新部署的流程定义的key
        BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
        String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
        //查询符合条件的总数
        long count = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))
                .count();
        //如果总数为0 直接返回空集合
        if (count == 0) {
            return new TablePageInfo<>(0L, Collections.EMPTY_LIST);
        }
        //进行分页
        List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery().processDefinitionKey(processDefinitionKey)
                .taskAssignee(String.valueOf(ShiroUtils.getUserId()))
                .listPage((qo.getPageNum() - 1) * qo.getPageSize(), qo.getPageSize());
        List<String> businessKeyList = new ArrayList<>();
        for (Task task : tasks) {
            //根据任务查询流程实例对象
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            //通过流程实例对象获取businessKey，存到集合中
            businessKeyList.add(instance.getBusinessKey());
        }
        List<CarPackageAudit> carPackageAudits = carPackageAuditMapper.queryTodoList(businessKeyList);

        return new TablePageInfo<>(count, carPackageAudits);
    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        //合理性校验
        CarPackageAudit audit = this.get(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BaseException("只有进行中的流程才能撤销");
        }
        //审核对象修改状态为流程撤销
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        carPackageAuditMapper.updateByPrimaryKey(audit);
        //服务单项更新状态 变为初始化状态
        busServiceItemService.changeStatus(audit.getServiceItemId(), BusServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "流程撤销");


    }

    @Override
    @Transactional
    public InputStream processImg(Long id) {
        //需要高亮的节点
        List<String> highLightedActivities = Collections.EMPTY_LIST;
        //需要高亮的连线
        List<String> highLightedFlows = Collections.EMPTY_LIST;
        CarPackageAudit audit = this.get(id);
        //这个id是CarPackageAudit的id 记录中只有instanceId
        String instanceId = audit.getInstanceId();
        //通过instanceId找到流程实例对象 ====》流程定义对象
        ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(instanceId)
                .singleResult();
        //获取目前活动的节点
        highLightedActivities = runtimeService.getActiveActivityIds(instance.getId());
        String processDefinitionId = instance.getProcessDefinitionId();
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(model, highLightedActivities, highLightedFlows, "宋体", "宋体", "宋体");
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }
}

